﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;

namespace StartSubMenu
{
    public partial class ItemsManagerForm : Form
    {
        string _xml = null;

        //--------------------------------------------------------------------------------
        public ItemsManagerForm(string itemsXmlPath)
        {
            InitializeComponent();
            _xml = itemsXmlPath;
        }
        //--------------------------------------------------------------------------------
        private void ItemsManagerForm_Load(object sender, EventArgs e)
        {
            dgvItems.Columns.Add("colPath", "Path");
            dgvItems.Columns.Add("colArguments", "Arguments");
            dgvItems.Columns.Add("colTitle", "Title");

            DataGridViewImageColumn colIcon = new DataGridViewImageColumn(true);
            colIcon.HeaderText = "Icon";
            colIcon.Name = "colIcon";
            dgvItems.Columns.Add(colIcon);

            int iconindex = dgvItems.Columns.Add("colIconPath", "Icon Path");
            dgvItems.Columns[iconindex].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

            LoadItemsFile();
        }
        //--------------------------------------------------------------------------------
        private void LoadItemsFile()
        {
            if (!File.Exists(_xml))
                return;

            XmlDocument doc = new XmlDocument();
            doc.Load(_xml);

            XmlNode root = doc.SelectNodes("/Items")[0];
            XmlNodeList items = doc.SelectNodes("//Item");
            List<XmlNode> tobeRemoved = new List<XmlNode>();

            foreach (XmlNode item in items)
            {
                string path = item.Attributes["path"] == null ? null : item.Attributes["path"].InnerText;
                string argument = item.Attributes["argument"] == null ? null : item.Attributes["argument"].InnerText;
                string title = item.Attributes["title"] == null ? null : item.Attributes["title"].InnerText;
                string icon = item.Attributes["icon"] == null ? null : item.Attributes["icon"].InnerText;

                if (path == null)
                    throw new Exception("missing path attribute");

                if (!File.Exists(path))
                {
                    tobeRemoved.Add(item);
                    continue;
                }

                dgvItems.Rows.Add(new object[] { path, argument, title, Icon.ExtractAssociatedIcon(icon), icon });
            }

            foreach (XmlNode item in tobeRemoved)
            {
                root.RemoveChild(item);
            }

            if (tobeRemoved.Count > 0)
                doc.Save(_xml);
        }
        //--------------------------------------------------------------------------------
        private void btnAdd_Click(object sender, EventArgs e)
        {
            AddItemForm additem = new AddItemForm();
            if (additem.ShowDialog() != DialogResult.OK)
                return;

            dgvItems.Rows.Add(new object[] { additem.AppPath, additem.Args, additem.Title, Icon.ExtractAssociatedIcon(additem.IconPath) , additem.IconPath });
        }
        //--------------------------------------------------------------------------------
        private void btnRemove_Click(object sender, EventArgs e)
        {
            if (dgvItems.SelectedRows.Count == 0)
                return;

            dgvItems.Rows.Remove(dgvItems.SelectedRows[0]);
        }
        //--------------------------------------------------------------------------------
        private void btnApply_Click(object sender, EventArgs e)
        {
            // write the items to the XML
            XmlDocument doc = new XmlDocument();
            XmlElement root = doc.CreateElement("Items");

            foreach(DataGridViewRow row in dgvItems.Rows)
            {
                XmlElement item = doc.CreateElement("Item");
                item.SetAttribute("path", row.Cells["colPath"].Value.ToString());
                item.SetAttribute("argument", row.Cells["colArguments"].Value.ToString());
                item.SetAttribute("title", row.Cells["colTitle"].Value.ToString());
                item.SetAttribute("icon", row.Cells["colIconPath"].Value.ToString());
                root.AppendChild(item);
            }

            doc.AppendChild(root);
            doc.Save(_xml);
            
            // mark closed successfully
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
        //--------------------------------------------------------------------------------
        private void ItemsManagerForm_DragEnter(object sender, DragEventArgs e)
        {
            try
            {
                FileInfo fi = new FileInfo((string)((string[])e.Data.GetData("FileNameW"))[0]);
                string ext = fi.Extension.ToLower();

                if (ext != ".exe" && ext != ".bat" && ext != ".lnk")
                    e.Effect = DragDropEffects.None;
                else
                    e.Effect = DragDropEffects.Copy;
            }
            catch { }
        }
        //--------------------------------------------------------------------------------
        private void ItemsManagerForm_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                FileInfo fi = new FileInfo((string)((string[])e.Data.GetData("FileNameW"))[0]);

                AddItemForm additem = new AddItemForm(fi.FullName, null, fi.FullName);
                if (additem.ShowDialog() != DialogResult.OK)
                    return;

                dgvItems.Rows.Add(new object[] { additem.AppPath, additem.Args, additem.Title, Icon.ExtractAssociatedIcon(additem.IconPath), additem.IconPath });
            }
            catch { }
        }
        //--------------------------------------------------------------------------------
        private void dgvItems_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewRow row = dgvItems.Rows[e.RowIndex];

            AddItemForm additem = new AddItemForm((string)row.Cells["colTitle"].Value, (string)row.Cells["colPath"].Value, (string)row.Cells["colArguments"].Value, (string)row.Cells["colIconPath"].Value);
            if (additem.ShowDialog() != DialogResult.OK)
                return;

            dgvItems.Rows.Add(new object[] { additem.AppPath, additem.Args, additem.Title, Icon.ExtractAssociatedIcon(additem.IconPath), additem.IconPath });
        }
        //--------------------------------------------------------------------------------
    }
}
